package com.ybg.share.core.shareapi;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvUtil;
import com.ybg.share.core.dbapi.entity.ShareStock;
import io.netty.util.concurrent.FastThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 获取财务报表数据
 */
@Slf4j
public abstract class AbstractStockFinancialApi {
    FastThreadLocal<ShareStock> threadLocal = new FastThreadLocal<ShareStock>();

    public Boolean execute(ShareStock stock) {
        threadLocal.set(stock);


        saveToDB();
        return Boolean.TRUE;
    }

    public abstract ShareStock getStock();

    public final FastThreadLocal<ShareStock> getThreadLocal() {
        return threadLocal;
    }

    public abstract String getUrl();

    private void saveToDB() {
        //   List<ShareStockDayK> shareStockDayKList = new ArrayList<>();
        CloseableHttpClient client = null;
        CloseableHttpResponse response;
        try {
            HttpGet httpGet = new HttpGet(getUrl());
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(), "GBK"));
            CsvData csvData = CsvUtil.getReader().read(in);
            if (csvData == null) {
                log.info("数据为空");
                return;
            }
            int headerSize = csvData.getRow(0).getRawList().size();
            //实际拥有的报告数
            int dataSize = headerSize - 1;
            if (dataSize == 0) {
                return;
            }
            toSaveDB(csvData);

            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 保存到具体数据库
     *
     * @param
     */
    public abstract void toSaveDB(CsvData csvData);

}
